<%@ page pageEncoding="UTF-8" %>
<%@ include file="/WEB-INF/views/common/taglibs-include.jsp" %>
<html>
<head>
    <title>系统用户列表</title>
    <script type="text/javascript" src="<c:url value="/assets/global/plugins/jquery.page.js"/>"></script>
    <script type="application/javascript" src="<c:url value="/assets/global/plugins/bootstrap-dialog/js/bootstrap-dialog.js"/>"></script>
	<link href="<c:url value="/assets/global/plugins/bootstrap-dialog/css/bootstrap-dialog.css"/>" rel="stylesheet" type="text/css">
	<script type="text/javascript" src="<c:url value="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js"/>"></script>
 	<script type="text/javascript" src="<c:url value="/assets/global/plugins/jquery-validation/js/additional-methods.min.js"/>"></script>
    <script>
	    var setting = {
	        data: {
	            simpleData: {
	                enable: true
	            }
	        },
	        check: {
	            enable: true
	        }
	    };

        var validator;
	    
        $(function () {

            validator = bindValidate();

            $('.table-scrollable').page({
                url: '<c:url value="/user/fsUser/query.do"/>',
                columns: [
                    {name: "序号", field: 'rowId', style: 'width:2%', checkbox: true},
                    {name: "用户名", field: 'name', style: 'width:13%','default':''},
                    {name: "手机号", field: 'phone', style: 'width:12%'},
                    {name: "注册时间", field: 'createTime', style: 'width:16%', sortable: true},
                    {name: "状态", field: 'status', style: 'width:6%', sortable: true, formatting: fromattingStatus},
                    {name: "操作", style: 'width:10%', formatting: formattingOperation}
                ],
                searchParams: {
                    'name': '${searchParam.name}',
                    'phone': '${searchParam.phone}',
                    'status': '${searchParam.status}'
                },
                'sortField': '${sys:toproperty(searchParam.sortField)}',
                'sortBy': '${searchParam.sortBy}',
                'currPage': '${pageBean.pageNum}'
            });

            $("#addBtn").click(function () {
                location.href = "<c:url value='/user/fsUser/initAdd.do'/>";
            });

            $("#toAssignRoleBtn").click(function () {
                var rows = $('.table-scrollable').page('selectedData');
                if (rows != null && rows.length == 1) {
                    resetCheckBox();
                    $.post("<c:url value='/user/smUser/queryUserRole.do'/>", {'userId': rows[0].rowId},
                            function (resp) {
                                setChecked(resp);
                                $("#stack1").modal('show');
                            },
                            'json'
                    );
                } else {
                    opertionTips("请选择一条记录");
                }
            });

            //分配角色 确认按钮事件
            $("#assignRoleBtn").click(function () {
                var checkIds = getSelectedCheckbox();
                if (checkIds == '') {
                    opertionTips("请选择");
                    return;
                }

                var userId = $('.table-scrollable').page('selectedData')[0].rowId;
                $.post("<c:url value='/user/fsUser/addUserRole.do'/>", {
                            'userId': userId,
                            'roleIds': checkIds.join(',')
                        },
                        function (resp) {
                            BootstrapDialog.alert({
                                title: '系统操作提示!',
                                message: resp.msg,
                                closable: true,
                                type: (resp.status == '0' ? BootstrapDialog.TYPE_SUCCESS : BootstrapDialog.TYPE_DANGER),
                                size: BootstrapDialog.SIZE_SMALL,
                                buttonLabel: '确 认',
                                callback: function () {
                                    if (resp.status == '0')  $("#stack1").modal('hide');
                                }
                            });
                        },
                        'json'
                );
            });

            $('#deleteBatchBtn').click(function () {
                var rowIdArr = new Array();
                var rows = $('.table-scrollable').page('selectedData');
                if (typeof(rows) == "undefined") {
                    BootstrapDialog.alert({
                        title: '系统操作提示!',
                        message: "请选择记录",
                        size: BootstrapDialog.SIZE_SMALL,
                        buttonLabel: '确 认',
                    });
                    return;
                } else {
                    for (var i = 0; i < rows.length; i++) {
                        rowIdArr.push(rows[i].rowId);
                    }
                }

                BootstrapDialog.confirm({
                    title: '系统操作提示!',
                    message: "确认删除么？",
                    size: BootstrapDialog.SIZE_SMALL,
                    btnCancelLabel: "取消",
                    btnOKLabel: "确认",
                    callback: function (resp) {
                        if (resp) {
							$.ajax({
				            	type:'POST',
				            	url :'<c:url value='/user/fsUser/deleteBatch.do'/>',
				            	data:{rowIds: rowIdArr.join(",")},
				            	dataType:'json',
				            	async:false,
				            	success:function(resp){
				            		BootstrapDialog.alert({
				                        title: '系统操作提示!',
				                        message: resp.msg,
				                        closable: true,
				                        type: (resp.status == '0' ? BootstrapDialog.TYPE_SUCCESS : BootstrapDialog.TYPE_DANGER),
				                        size: BootstrapDialog.SIZE_SMALL,
				                        buttonLabel: '确 认',
				                        callback: function () {
				                            if (resp.status == '0') $('.table-scrollable').page("reload");
				                        }
				                    });
				            	},
				            	error:function(resp){
				            		if(resp.status == '403')window.location.href = '<c:url value="/accessDefine.do"/>';
				            	}
				            })
                        }
                    }
                });

            });

            $("#toResetPwd").click(function () {
                $("#pwd1").val("");
                $("#pwd2").val("");
                var rows = $('.table-scrollable').page('selectedData');
                if (rows != null && rows.length == 1) {
                    $("#stack2").modal("show");
                } else {
                    opertionTips("请选择一条记录");
                }
            });

            $("#resetPwdBtn").click(function () {
                var rows = $('.table-scrollable').page('selectedData');
                var pwd1 = $("#pwd1").val();
                var pwd2 = $("#pwd2").val();
                if (pwd1 == "" || pwd2 == "") {
                    opertionTips("密码不能为空");
                    return;
                } else if (pwd1 != pwd2) {
                    opertionTips("两次密码不一致");
                    return;
                }
                
                $.ajax({
                	type:'POST',
	            	url :'<c:url value='/user/fsUser/resetPwd.do'/>',
	            	data:{"rowId": rows[0].rowId, "password": pwd1},
	            	dataType:'json',
	            	async:false,
	            	success:function(resp){
	            		BootstrapDialog.alert({
	                        title: '系统操作提示!',
	                        message: resp.msg,
	                        closable: true,
	                        type: (resp.status == '0' ? BootstrapDialog.TYPE_SUCCESS : BootstrapDialog.TYPE_DANGER),
	                        size: BootstrapDialog.SIZE_SMALL,
	                        buttonLabel: '确 认',
	                        callback: function () {
	                            if (resp.status == '0') $("#stack2").modal("hide");
	                        }
	                    });
	            	},
	            	error:function(resp){
	            		if(resp.status == '403')window.location.href = '<c:url value="/accessDefine.do"/>';
	            	}
                })
            });
        });

        function setUserCommTree(userId) {
            $.ajax({
                type: 'POST',
                dataType: "json",
                async: false,
                url: "<c:url value='/community/user/jsonCommunitys.do'/>?userId="+userId,//请求的action路径
                success: function (data) { //请求成功后处理函数。
                    $.fn.zTree.init($("#userCommunityTree"), setting, eval(data));
                }
            });
        }
        //checkBox取消选中
        function resetCheckBox() {
            $(".icheck-list input[type=checkbox]").attr("checked", false);
        }

        //获取选中的模块
        function getSelectedCheckbox() {
            var checkIds = new Array();
            $(".icheck-list input[type=checkbox]").each(function () {
                if (this.checked) {
                    checkIds.push($(this).val());
                }
            });
            return checkIds;
        }

        //设置模块checkbox选中
        function setChecked(checkIds) {
            var cidArr = checkIds.split(",");
            $(".icheck-list input[type=checkbox]").each(function () {
                for (var i in cidArr) {
                    if ($(this).val() == cidArr[i]) {
                        $(this).attr("checked", true);
                    }
                }
            });
        }

        function formattingOperation(index, row) {
            var operation = "";
            operation += '<a title="修改" onclick="initEdit(' + row.rowId + ')" class="btn btn-warning">修改</a><span style="width:3px;">&nbsp;</span>';
            operation += '<a title="删除" onclick="deleteRow(' + row.rowId + ')" class="btn">删除</a><span style="width:3px;">&nbsp;</span>';

            if (row.status == '0') {
                operation += '<a title="禁用" onclick="disableUser(' + row.rowId + ')" class="btn btn-yellow">禁用</a><span style="width:3px;">&nbsp;</span>'
            }
            else {
                operation += '<a title="启用" onclick="enableUser(' + row.rowId + ')" class="btn btn-yellow">启用</a><span style="width:3px;">&nbsp;</span>'
            }
            return operation;
        }


        function view(rowId){
            location.href = "<c:url value='/user/fsUser/view.do?rowId='/>"+rowId;
        }

        function formattingIsGag(index, row) {
            return "";
        }

        function fromattingStatus(index, row) {
        	if(row){
        		if(row.status=='0')return "正常";
        	}
         	return "禁用";
        }
        function fromattingAttribute(index, row) {
            return "";
        }

        function deleteRow(rowId) {
            BootstrapDialog.confirm({
                title: '系统操作提示!',
                message: "确认删除么？",
                size: BootstrapDialog.SIZE_SMALL,
                btnCancelLabel: "取消",
                btnOKLabel: "确认",
                callback: function (resp) {
                    if (resp) {
                        $.ajax({
			            	type:'POST',
			            	url :'<c:url value='/user/fsUser/delete.do'/>',
			            	data:{rowId: rowId},
			            	dataType:'json',
			            	async:false,
			            	success:function(resp){
			            		BootstrapDialog.alert({
			                        title: '系统操作提示!',
			                        message: resp.msg,
			                        closable: true,
			                        type: (resp.status == '0' ? BootstrapDialog.TYPE_SUCCESS : BootstrapDialog.TYPE_DANGER),
			                        size: BootstrapDialog.SIZE_SMALL,
			                        buttonLabel: '确 认',
			                        callback: function () {
			                            if (resp.status == '0') $('.table-scrollable').page("reload");
			                        }
			                    });
			            	},
			            	error:function(resp){
			            		if(resp.status == '403')window.location.href = '<c:url value="/accessDefine.do"/>';
			            	}
			            })
                    }
                }
            });
        }

        function initEdit(rowId) {
            location.href = "<c:url value='/user/smUser/initEdit.do?rowId='/>" + rowId;
        }

        function disableUser(rowId) {
				$.ajax({
            	type:'POST',
            	url :'<c:url value='/user/fsUser/disable.do'/>',
            	data:{rowId:rowId},
            	dataType:'json',
            	async:false,
            	success:function(resp){
            		BootstrapDialog.alert({
                        title: '系统操作提示!',
                        message: resp.msg,
                        closable: true,
                        type: (resp.status == '0' ? BootstrapDialog.TYPE_SUCCESS : BootstrapDialog.TYPE_DANGER),
                        size: BootstrapDialog.SIZE_SMALL,
                        buttonLabel: '确 认',
                        callback: function () {
                            if (resp.status == '0') $('.table-scrollable').page("reload");
                        }
                    });
            	},
            	error:function(resp){
            		if(resp.status == '403')window.location.href = '<c:url value="/accessDefine.do"/>';
            	}
            })
        }

        function enableUser(rowId) {
            $.ajax({
            	type:'POST',
            	url :'<c:url value='/user/fsUser/enable.do'/>',
            	data:{rowId:rowId},
            	dataType:'json',
            	async:false,
            	success:function(resp){
            		BootstrapDialog.alert({
                        title: '系统操作提示!',
                        message: resp.msg,
                        closable: true,
                        type: (resp.status == '0' ? BootstrapDialog.TYPE_SUCCESS : BootstrapDialog.TYPE_DANGER),
                        size: BootstrapDialog.SIZE_SMALL,
                        buttonLabel: '确 认',
                        callback: function () {
                            if (resp.status == '0') $('.table-scrollable').page("reload");
                        }
                    });
            	},
            	error:function(resp){
            		if(resp.status == '403')window.location.href = '<c:url value="/accessDefine.do"/>';
            	}
            })
        }

        function bindValidate(){
			
            return $('#tableForm2').validate({
                errorElement: 'span',
                errorClass: 'help-block help-block-error',
                focusInvalid: false,
                ignore: "",
                messages: {
                    pwd1:{
                        required:"名称不能为空！"
                    },
                    pwd2:{
                        required:"编号不能为空！"
                    }

                },
                rules: {
                    pwd1: {
                        required: true
                    },
                    pwd2: {
                        required: true
                    }

                },

                invalidHandler: function (event, validator) { //display error alert on form submit
                },

                highlight: function (element) { // hightlight error inputs
                    $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change done by hightlight
                    $(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label.closest('.form-group').removeClass('has-error'); // set success class to the control group
                }
            });
        }

        function opertionTips(msg) {
            BootstrapDialog.alert({
                title: '系统操作提示!',
                message: msg,
                size: BootstrapDialog.SIZE_SMALL,
                buttonLabel: '确 认',
            });
        }
    </script>
</head>
<body>
<div class="portlet light bordered">
    <div class="portlet-body">
        <form id="searchForm" method="post" name="searchForm">
            <table id="mainTable" style="width: 100%;font-size: 14px;">
                <tr>
                	<td>
                        <input type="text" class="col-sm-4" name="name" value="${searchParam.name}" placeholder="请输入姓名">
                    </td>
                </tr>
                <tr>
                 <td style="height: 3px;"></td>
                </tr>
                <tr>
                	<td>
                        <input type="text" class="col-sm-4" name="phone" value="${searchParam.phone}" placeholder="请输入手机号">
                    </td>
                </tr>
                <tr>
                	<td style="width:40px;text-align: right;padding-top: 10px;" colspan="4">
                        <a id="addBtn" class="btn btn-pink">
                            <i class="fa fa-plus"></i>&nbsp;新&nbsp;增
                        </a>
                        <a id="deleteBatchBtn" class="btn btn-gray">
                            <i class="fa fa-trash-o"></i>批量删除
                        </a>
                        <a id="toAssignRoleBtn" class="btn btn-info">
                            <i class="fa fa-cog"></i>&nbsp;分配角色
                        </a>
                        <a id="toResetPwd" class="btn btn-warning">
                            <i class="fa fa-cubes"></i>&nbsp;重置密码
                        </a>
                        <a id="searchBtn" class="btn btn-purple">
                            <i class="fa fa-search"></i>&nbsp;查&nbsp;询
                        </a>
                    </td>
                </tr>
            </table>
        </form>
        <div style="height: 5px;">&nbsp;</div>
        <div class="table-scrollable">

        </div>
    </div>


    <div id="stack1" class="modal fade" tabindex="-1" data-width="400">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">
                        <i class="fa fa-wrench"></i>
                        <span class="caption-subject bold uppercase" id="modalTitle1">分配角色</span>
                    </h4>
                </div>

                <div class="modal-body">
                    <form id="tableForm1" method="post" action="<c:url value='/sys/role/add.do'/>">
                        <div class="input-group">
                            <div class="icheck-list">
                                <c:forEach items="${roleList }" var="item">
                                    <label><input type="checkbox" name="roleCheck" class="icheck"
                                                  value="${item.rowId }"> ${item.name } </label>
                                </c:forEach>
                            </div>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn">取消</button>
                    <button type="button" id="assignRoleBtn" class="btn red">确认</button>
                </div>
            </div>
        </div>
    </div>

    <div id="stack2" class="modal fade" tabindex="-1" data-width="350">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">
                        <i class="fa fa-wrench"></i>
                        <span class="caption-subject bold uppercase" id="modalTitle2">重置密码</span>
                    </h4>
                </div>

                <div class="modal-body form">
                    <form id="tableForm2" method="post" action="">
                        <div class="row form-group">
                            <div class="col-md-9">
                                <div class="form-group">
                                    <label class="control-label col-md-3">新密码：</label>

                                    <div class="col-md-8">
                                        <input type="password" class="form-control" id="pwd1" name="pwd1" maxlength="15"
                                               placeholder="请输入" onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"/>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-9">
                                <div class="form-group">
                                    <label class="control-label col-md-3">确认密码：</label>

                                    <div class="form-group col-md-8">
                                        <input type="password" class="form-control" id="pwd2" name="pwd2"
                                               placeholder="请输入" onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"/>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn">取消</button>
                    <button type="button" id="resetPwdBtn" class="btn red">确认</button>
                </div>
            </div>
        </div>
    </div>

</div>
<script>
    jQuery(document).ready(function () {
        $('#searchBtn').click(function () {
            $('.table-scrollable').page("reload", {'searchParams': $('#searchForm').serialize()});
        });
    });
</script>
</body>
</html>
